package dmsxl.zifuchuan;

/**
 * Author: Zhang Dongwei
 * Date: 2023/4/22 12:17
 * Offer 58 - II. 左旋转字符串
 */
public class zfc5_offer58_II {

    public static void main(String[] args) {
        String s = "abcdefg";
        int k = 2;
        System.out.println(reverseLeftWords3(s, k));
    }

//    自己写的，效果较差
    public static String reverseLeftWords1(String s, int n) {
        StringBuilder sb = new StringBuilder();
        for (int i = n; i < s.length(); i++){
            sb.append(s.charAt(i));
        }
        for (int i = 0; i < n; i++){
            sb.append(s.charAt(i));
        }
        return sb.toString();
    }
//    自己写的，效果较差
    public static String reverseLeftWords2(String s, int n) {
        String temp = s.substring(0, n);
        System.out.println(temp);
        char[] chars = s.toCharArray();
        for (int i = 0; i < s.length() - n; i++){
            chars[i] = chars[n+i];
        }
        System.out.println(chars);
        for (int j = 0; j < n; j++){
            chars[s.length() - n + j] = temp.charAt(j);
        }
        return new String(chars);
    }

//    题解1，效果也不好
    public static String reverseLeftWords3(String s, int n) {
        int len=s.length();
        StringBuilder sb=new StringBuilder(s);
        reverseString(sb,0,n-1);
        reverseString(sb,n,len-1);
        return sb.reverse().toString();
    }
    public static void reverseString(StringBuilder sb, int start, int end) {
        while (start < end) {
            char temp = sb.charAt(start);
            sb.setCharAt(start, sb.charAt(end));
            sb.setCharAt(end, temp);
            start++;
            end--;
        }
    }

//    题解2，效果较好
    public static String reverseLeftWords(String s, int n) {
        char[] chars = s.toCharArray();
        reverse(chars, 0, chars.length - 1);
        reverse(chars, 0, chars.length - 1 - n);
        reverse(chars, chars.length - n, chars.length - 1);
        return new String(chars);
    }

    public static void reverse(char[] chars, int left, int right) {
        while (left < right) {
            chars[left] ^= chars[right];
            chars[right] ^= chars[left];
            chars[left] ^= chars[right];
            left++;
            right--;
        }
    }
}
